package mws;

import jakarta.annotation.PostConstruct;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;



public class RedisLuaLimiter implements Limiter {


    private  DefaultRedisScript<Long> redisScript;

    private RedisTemplate<String,String> redisTemplate;

    @PostConstruct
    public void start(){
        redisScript = new DefaultRedisScript<>();
        ClassPathResource classPathResource = new ClassPathResource("redis/limit.lua");
        try {
            InputStream inputStream = classPathResource.getInputStream();
            redisScript.setScriptSource(new ResourceScriptSource(classPathResource));
            redisScript.setResultType(Long.class);
        } catch (IOException e) {
            System.out.println("RedisLuaLimiter start error");
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean tryAcquire() {
        Long result = redisTemplate.execute(redisScript, Collections.singletonList("key"), "10");
        return result == 1L;
    }

    @Override
    public int acquire() {
        if(!tryAcquire()){
            return 0;
        }
        return 1;
    }
}
